package cn.gailvlun.gll.util;

import java.util.concurrent.TimeUnit;

import io.reactivex.Completable;
import io.reactivex.CompletableSource;
import io.reactivex.CompletableTransformer;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.Single;
import io.reactivex.SingleSource;
import io.reactivex.SingleTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;



public class RxUtil {

    public static Observable<Long> timer(long delay, TimeUnit timeUnit) {
        return Observable.timer(delay, timeUnit)
                .observeOn(AndroidSchedulers.mainThread());
    }

    public static Observable<Long> timer(long delay) {
        return timer(delay, TimeUnit.SECONDS);
    }

    public static Observable<Long> countDown(final long countDown) {
        return Observable.interval(0, 1, TimeUnit.SECONDS)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        return countDown - aLong;
                    }
                })
                .take(countDown + 1)
                .compose(RxUtil.<Long>applyScheduler());
    }

    public static <T> ObservableTransformer<T, T> applyScheduler() {
        return new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> upstream) {
                return upstream
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread(), false, 100);
            }
        };
    }

    public static <T> SingleTransformer<T, T> applySingleScheduler() {
        return new SingleTransformer<T, T>() {
            @Override
            public SingleSource<T> apply(Single<T> upstream) {
                return upstream
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    public static CompletableTransformer applyNullScheduler() {
        return new CompletableTransformer() {
            @Override
            public CompletableSource apply(Completable upstream) {
                return upstream.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

}
